package Proj_pack;

import java.io.File;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;

public class netz2135 {
	// static List<Knoten> alleKnoten;
	static LinkedBlockingDeque<Mash> unstable = new LinkedBlockingDeque<Mash>();
	static Maschen maschen;
	static int res;
	static CountDownLatch resultWait;
	static CountDownLatch graphWait;
	static CountDownLatch edgeWait;
	static int many;

	public netz2135() {
		unstable = new LinkedBlockingDeque<Mash>();
		res = 0;
	}

	// test main
	public static void main(String[] argv) {
		final Graph gr = new Graph();
		edgeWait = new CountDownLatch(argv.length); // damit Parser aufeinander
													// warten
		graphWait = new CountDownLatch(argv.length); // damit main auf den(die)
														// parser wartet
		// many = 100; // kann benutzt werden wenn untere zeile auskommentiert
		many = Runtime.getRuntime().availableProcessors() + 1;

		for (int i = 0; i < argv.length; i++) {
			final File file = new File(argv[i]);
			(new Thread(new Runnable() {
				public void run() {
					new xml2graph_parser(gr).createGraph(file);
					graphWait.countDown();
				};
			})).start();
		}
		boolean b1 = false;
		do {
			b1 = false;
			try {
				graphWait.await();
			} catch (InterruptedException e1) {
				b1 = true;
			}
		} while (b1);
		maschen = new Maschen(gr);
		// System.out.println(maschen);
		unstable.addAll(maschen.getMaschen());
		resultWait = new CountDownLatch(many);
		for (int i = 0; i < many; i++) {
			new Thread(new Worker()).start();
		}
		boolean b2 = false;
		do {
			b2 = false;
			try {
				resultWait.await();
			} catch (InterruptedException e1) {
				b2 = true;
			}
		} while (b2);
		// do{
		// try {resultWait.await();}catch(InterruptedException e1){}
		// }while(resultWait.getCount()<many);

		// System.err.println("maschen: " + maschen);
		res = maschen.getMaschen().size();
		// System.out.println("threads: "+ many + " Anzahl Stromnetze: " + res);
		 System.exit(res); //TODO muss fuer JUnit-test auskommentiert werden,
		// ABER fuer jar-file muss es drin sein!!!

	}

	public int getRes() {
		return res;
	}

	public Maschen getMaschen() {
		return maschen;
	}
}